package com.xunyin.modules.meituan.service.impl;


import com.github.pagehelper.PageInfo;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.meituan.tuangou.MeiTuanCouponService;
import com.xunyin.meituan.tuangou.request.CouponConsumeParam;
import com.xunyin.meituan.tuangou.result.CouponConsumeResult;
import com.xunyin.meituan.tuangou.result.CouponPrepareResult;
import com.xunyin.meituan.tuangou.result.SetMealListResult;
import com.xunyin.modules.meituan.domain.TMeituanStoremap;
import com.xunyin.modules.meituan.param.MeituanParam;
import com.xunyin.modules.meituan.service.TMeituanStoremapService;
import com.xunyin.modules.meituan.service.dto.TMeituanStoremapQueryCriteria;
import com.xunyin.modules.meituan.service.mapper.TMeituanStoremapMapper;
import com.xunyin.modules.recharge.domain.TRechargeSet;
import com.xunyin.modules.recharge.service.TRechargeSetService;
import com.xunyin.modules.shareorder.param.TShareOrderParam;
import com.xunyin.modules.shareorder.service.TShareOrderService;
import com.xunyin.utils.DateUtil;
import com.xunyin.utils.OrderNoUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @date 2022-02-27
 */
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TMeituanStoremapServiceImpl extends BaseServiceImpl<TMeituanStoremapMapper, TMeituanStoremap> implements TMeituanStoremapService {


    private final IGenerator generator;

    @Autowired
    private MeiTuanCouponService meiTuanCouponService;

    @Autowired
    private TRechargeSetService tRechargeSetService;

    private TShareOrderService tShareOrderService;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(TMeituanStoremapQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<TMeituanStoremap> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<TMeituanStoremap> queryAll(TMeituanStoremapQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(TMeituanStoremap.class, criteria));
    }


    /**
     * 美团门店套餐映射
     *
     * @param queryParam
     * @return
     */
    @Override
    public int getSetMealList(MeituanParam queryParam) {
        // 查询美团门店套餐映射接口，获取套餐列表
        SetMealListResult setMealListResult = meiTuanCouponService.querySetMealList(queryParam.getDealStatus());
        if (setMealListResult != null && setMealListResult.getCode().equals("OP_SUCCESS")) {
            List<SetMealListResult.SetMeal> data = setMealListResult.getData();
            if (data != null && data.size() > 0) {
                // 根据项目ID（dealId）判断,如果本系统没有对应的套餐信息，则添加同步美团套餐信息到本系统套餐表
                // 如果已存在，则美团套餐信息
                for (SetMealListResult.SetMeal setMeal : data) {
                    Integer dealId = setMeal.getDealId();
                    TRechargeSet tRechargeSet = tRechargeSetService.selectBydealId(dealId);
                    // 如果存在则更新套餐信息
                    if (tRechargeSet != null) {
/*

                        setMeal.getDealStatus()

                        setMeal.getIsVoucher()
                        // isVoucher	boolean
                        //是否是代金券，true为代金券，false为套餐
                        */
                        String beginTime = DateUtil.timestampToDate(setMeal.getBeginTime());
                        String endTime = DateUtil.timestampToDate(setMeal.getDealEndTime());
                        tRechargeSet.setValidityDateStart(new Date(beginTime));
                        tRechargeSet.setValidityDateEnd(new Date(endTime));
                        tRechargeSet.setName(setMeal.getDealTitle());
                        tRechargeSet.setPrice(setMeal.getDealPrice().intValue());
                        tRechargeSetService.updateById(tRechargeSet);
                    } else {

                        tRechargeSet = new TRechargeSet();
                        String beginTime = DateUtil.timestampToDate(setMeal.getBeginTime());
                        String endTime = DateUtil.timestampToDate(setMeal.getDealEndTime());
                        tRechargeSet.setValidityDateStart(new Date(beginTime));
                        tRechargeSet.setValidityDateEnd(new Date(endTime));
                        tRechargeSet.setName(setMeal.getDealTitle());
                        tRechargeSet.setPrice(setMeal.getDealPrice().intValue());
                        tRechargeSet.setDealId(setMeal.getDealId());
                        tRechargeSet.setStatus(1);
                        tRechargeSet.setEnable(1);

                        tRechargeSetService.save(tRechargeSet);
                    }
                }
            }
        }
        return 1;
    }


    /**
     * 用户兑换核销验券，根据券码核销验券
     *
     * @param queryParam
     * @return
     */
    @Override
    public int exchangeVerifiRecharge(MeituanParam queryParam) {
        // 调用美团验券接口，如果验券成功，则在本系统的对应用户，添加一张卡券
        CouponPrepareResult couponPrepareResult = meiTuanCouponService.couponPrepare(queryParam.getCouponCode());
        CouponPrepareResult.CouponPrepare couponPrepare = couponPrepareResult.getData();
        if (couponPrepare != null) {
            Integer dealId = couponPrepare.getDealId();
            // 根据项目id,查询本系统的卡券套餐表，对应套餐
            TRechargeSet tRechargeSet = tRechargeSetService.selectBydealId(dealId);
            // 执行验券
            CouponConsumeParam couponConsumeParam = new CouponConsumeParam();
            couponConsumeParam.setEId(tRechargeSet.getTeaHouseId().toString());
            couponConsumeParam.setCouponCode(queryParam.getCouponCode());
            couponConsumeParam.setEName(tRechargeSet.getTeaHouseName());
            couponConsumeParam.setCount(couponPrepare.getCount());
            String orderNo = OrderNoUtil.getOrderNo("1012", "");//获取订单号
            couponConsumeParam.setEOrderId(orderNo);
            CouponConsumeResult couponConsumeResult = meiTuanCouponService.couponConsume(couponConsumeParam);
            // 验券成功
            if (couponConsumeResult.getCode().equals("OP_SUCCESS")) {
                // 生成一条购买套餐订单，标识为美团兑换
                TShareOrderParam tShareOrderParam = new TShareOrderParam();
                tShareOrderParam.setOrderNo(orderNo);
                tShareOrderParam.setOpenId(queryParam.getOpenId());
                tShareOrderParam.setUserPhone(queryParam.getUserPhone());
                tShareOrderParam.setPageId(queryParam.getPageId());
                tShareOrderParam.setRechargeSetId(tRechargeSet.getId());
                tShareOrderParam.setTeaHouseId(tRechargeSet.getTeaHouseId());
                tShareOrderService.createRechargeOrder(tShareOrderParam);
            }
        }
        return 1;
    }
}
